# -*- coding: utf-8 -*-
from api import api, GlobalError
from bson import ObjectId
from config import OSS_BUCKET, OSS_APP_ID, OSS_APP_KEY, OSS_HOST, \
    OSS_INTERNAL_HOST, OSS_URL_TIME_OUT
from flask import jsonify, request, Response, abort
from lib.oss.oss_api import OssAPI
from util.oss_helper import oss_url_upload
import time
from PIL import Image
from urllib2 import urlopen
import cStringIO
import StringIO
@api.route('/image-url', methods=['POST'])
def get_image_upload_url():
    '''
## 获取上传图片的 Url

    POST /api/image-url

Parameters:

* `suffix` (required) - 图片后缀
* `contentType` (required) - content type

Return:

* `url` (string) - Url to upload image

Errors: `4`
    '''
    suffix = request.form.get('suffix', '')
    content_type = request.form.get('contentType', None)
    if suffix not in ['bmp', 'gif', 'jpeg', 'jpg', 'png']:
        return jsonify(stat=0, **GlobalError.REFUSED_FILE_FORMAT), 403
    filename = '.'.join([str(ObjectId()) + str(int(time.time())), suffix])
    sign_url = oss_url_upload(OSS_BUCKET, filename, OSS_URL_TIME_OUT, content_type)
    print sign_url

    return jsonify(stat=1, url=sign_url)


@api.route('/image', methods=['POST'])
def upload_image_url():
    '''
## 上传图片

    POST /api/image

Parameters:

* `image` (文件, required)

Return:

* `url` (string) - Url of image

Errors: `4`
    '''
    image_file = request.files['image']
    suffix = image_file.filename.split('.')[-1]
    if suffix not in ['bmp', 'gif', 'jpeg', 'jpg', 'png']:
        return jsonify(stat=0, **GlobalError.REFUSED_FILE_FORMAT), 403

    filename = '.'.join([str(ObjectId()) + str(int(time.time())), suffix])
    oss = OssAPI(OSS_INTERNAL_HOST, OSS_APP_ID, OSS_APP_KEY)
    oss.put_object_from_string(OSS_BUCKET, filename, image_file.stream.read())

    url = 'http://' + OSS_BUCKET + '.' + OSS_HOST + '/' + filename

    return jsonify(stat=1, url=url)


@api.route('/thumbnail/<string:filename>', methods=['GET'])
def get_thumbnail(filename=None):
    '''
## 获取特定文件名的缩略图

    GET /api/thumbnail/<str:image_name>

Parameters:

* `width` - 图片宽度

Return:

* `image` (文件) - 处理后的图片

    '''
    width = int(request.args.get('width', 300))
    url = 'http://' + OSS_BUCKET + '.' + OSS_HOST + '/' + filename
    try:
        res = urlopen(url)
    except:
        abort(404)
    image_original = cStringIO.StringIO(res.read())
    image = Image.open(image_original)
    w, h = image.size
    height = int(width * 1.0 / w * h)
    image = image.resize((width, height), Image.ANTIALIAS)
    o = StringIO.StringIO()
    image.save(o, "JPEG")
    return Response(o.getvalue(), mimetype='image/jpeg')